/**
 * an object to manipulate with Request Query String
 * @author max klymyshyn
 * (c) Sonettic, 2009
 * www.sonettic.com
 */
 


/**
 * query string parser/renderer
 */
function queryStringParser(q){
	if(q == null)q = location.href;
	
	this.args = {};
	this.source_string = q;

	return this;
}


queryStringParser.prototype = {
	/**
	 * parse string q to query strin argument (field args)
	 * @param q string with HTTP GET string param
	 * @return boolean
	 */	
	parse : function(q){
		if(q == null)q = this.source_string;
		//skip url if it's available
		if(q.indexOf('?') > 0){
			q = q.substring(q.indexOf('?') + 1, q.length);
		}
		
		var pairs = q.split('&');
		
		for(var p in pairs){
			var pair = pairs[p].split('=');
			if(pair.length == 2){
				this.add_item(decodeURI(pair[0]), decodeURI(pair[1]));
			}		
		}
		return this;
	},
	
	/**
	 * reset storage of the QS variables
	 */	
	clear : function(){
		this.args = {};
		this.source_string = '';
		return true;
	},
	
	/**
	 * method to get variable value by name
	 * @param name name of variable
	 * @return value of th evariable name
	 */
	get : function(name){
		if(name == null)return null;
		if(!this.args[name])return null;
		return this.args[name];
	},
	
	/** 
	 * get list of all query string params
	 * @return Array
	 */
	list : function(){
		return this.args;	
	},
	
	/**
	 * remove an variable from the list of QS arguments
	 * @param name name of the variable
	 * @return true if vairable is removed or false if it's not
	 */
	del : function(name){
		if(name == null)return false;
		if(this.args[name])return delete this.args[name];	
		return false;
	},
	
	/** 
	 * add one item to list of query strin arguments
	 * @param param name of variable
	 * @param value value of an argument
	 * @return boolean
	 */
	add_item : function(param, value){
		if(param == null)return false;
		if(value == null)value='null';
		this.args[param] = value;
	},
	
	/**
	 * add one variable with value to query strin arguments
	 * or add many elements (param as an array)
	 * @param param name of variable or array with couple of variables
	 * @param value variable name value or null
	 * @return boolean true or false
	 */
	add : function(param, value){
		if(value == null && param.constructor.toString().indexOf('Array') != -1){
			for(var v in param){
				this.add_item(v, param[v]);
			}
			return true;
		}
		this.add_item(param, value);
	},
	
	/**
	 * render query args to HTTP GET string
	 * 
	 */
	render : function(){
		var pairs = [];
	
		for(var v in this.args){
			var value = this.args[v] != null ? this.args[v] : 0;
			pairs[pairs.length] = escape(v) + '=' + escape(value);
		}
		return pairs.join('&');
	}
};




